<template>
  <BasicModal v-bind="$attrs" @ok="handleOk" @register="registerModal">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue';
  import mcApi from 'mc-c2b2m-operator-api';
  import { uploadFormSchema } from './data';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicModal, useModalInner } from '@/components/Modal';

  const { ProductionModule } = mcApi;
  const { BluePaperApi } = ProductionModule;

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: uploadFormSchema,
    baseColProps: { span: 22 },
    showActionButtonGroup: false,
  });

  const type = ref<string>('');
  // 是否原文件上传
  const ifAttachment = computed(() => {
    return type.value === 'attachment';
  });
  const [registerModal, { setModalProps }] = useModalInner(async (data) => {
    type.value = data?.type || 'attachment';
    await resetFields();
    await setFieldsValue(data);
    setModalProps({
      minHeight: 50,
      confirmLoading: false,
      title: `上传${ifAttachment.value ? '原文件' : '蓝纸'}`,
    });
  });

  const { createMessage } = useMessage();
  const emits = defineEmits(['success']);
  async function handleOk() {
    try {
      const values: any = await validate();
      const { url } = values;
      if (ifAttachment.value) {
        const tempList = url.split('/');
        values.attachmentList = [{ name: tempList[tempList.length - 1], url: url[0] }];
      } else {
        values.bluePrintImgUrl = url[0];
      }
      setModalProps({ confirmLoading: true });
      const fun = ifAttachment.value
        ? BluePaperApi.uploadSalesProductBatchAttachment
        : BluePaperApi.uploadSalesProductBatchBluePrint;
      await fun(values);
      createMessage.success(`上传${ifAttachment.value ? '原文件' : '蓝纸'}成功！`);
      emits('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
